package com.zz.shop.dao.impl;

import com.zz.shop.dao.UserDao;
import com.zz.shop.entity.User;
import com.zz.shop.util.DbUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr=new QueryRunner(DbUtil.getDataSource());

    @Override
    public User getUserByUsername(String username) throws SQLException {
        String sql =
                "select " +
                        "`u_id` 'uid',`u_name` 'uname',`u_password` 'upassword'," +
                        "`u_email` 'uemail',`u_sex` 'usex',`u_status` 'ustatus'," +
                        "`u_code` 'ucode',`u_role` 'urole'" +
                        "from user "+
                        " where u_name=?";
        return qr.query(sql, new BeanHandler<>(User.class),username);
    }

    @Override
    public int activate(int uid) throws SQLException {
        String sql = "update user set u_status =1 where u_id=?";

        return qr.update(sql,uid);
    }

    @Override
    public User getUserByEmailAndCode(String email, String code) throws SQLException {
        String sql =
                "select " +
                        "`u_id` 'uid',`u_name` 'uname',`u_password` 'upassword'," +
                        "`u_email` 'uemail',`u_sex` 'usex',`u_status` 'ustatus'," +
                        "`u_code` 'ucode',`u_role` 'urole'" +
                        "from user "+
                        " where u_email=? and u_code=?";
        return qr.query(sql,new BeanHandler<>(User.class),email,code);
    }

    @Override
    public int insertUser(User u) throws SQLException {
        String sql="insert into user values (default,?,?,?,?,?,?,?)";
        return qr.update(sql,
                u.getUname(),
                u.getUpassword(),
                u.getUemail(),
                u.getUsex(),
                u.getUstatus(),
                u.getUcode(),
                u.getUrole());
    }

    @Override
    public User findUserByName(String username) throws SQLException {
        String sql="select " +
                "`u_id` 'uid',`u_name` 'uname',`u_password` 'upassword',`u_email` 'uemail',`u_sex` 'usex'," +
                "`u_status` 'ustatus',`u_code` 'ucode',`u_role` 'urole' " +
                "from user " +
                "where u_name=? ";
        return qr.query(sql,new BeanHandler<>(User.class),username);
    }


}
